
var utilObj = null;
var force_p2p = true;

function getSecUrl( url ) {
	if ( url.indexOf("{TID}") < 0 ) {
		if ( force_p2p ) {
			var nurl = url.replace(/http:\/\/127.0.0.1.*?url=/, "");
			url = "http://127.0.0.1:14188/playlist/play.m3u8?url=" + nurl;
		}
		return url;
	}

	if ( ! utilObj ) {
		utilObj = wae.create("Utils.Utils");
	}

	// var tid = Math.floor( 10000000 + (Math.random() * 8999999 ));
	var tid = localStorage.getItem("Player_Terminal_ID");
	if ( tid == null || tid.length < 6 ) {
		var did = localStorage.getItem("DeviceInfo_RID");
		if ( did == null )
			tid = Math.floor( 10000000 + (Math.random() * 8999999 ));
		else
			tid = did + Math.floor( 1000000 + (Math.random() * 899999 ));
		localStorage.setItem("Player_Terminal_ID", tid );
	}

	var uri =  url.replace(/http:\/\/127.0.0.1.*?url=/, "").replace(/http:\/\/.*?\//, "/").replace( /\?.*$/, "");
	var seed= "tvata nginx auth module";
	var day = Math.floor( (new Date()).getTime() / 1000 / 3600 / 24 );
	var checkdata = seed + uri + tid + day ;
	var checksum1 = utilObj.md5( checkdata );
	var rurl = url.replace( /\{TID\}/, tid ).replace( /\{TSUM\}/, checksum1 );
	rurl = rurl.replace( /\&amp;/g, "&" );
	if ( force_p2p ) {
		var nurl = rurl.replace(/http:\/\/127.0.0.1.*?url=/, "");
		rurl = "http://127.0.0.1:14188/playlist/play.m3u8?url=" + nurl;
	}
	// console.log("get url : " + rurl );
	return rurl;
}



function CPUInfo() {
	this.total = 1;
	this.idle = 1;
	this.fobj = null;

	this.getusage = function() {
		if ( ! this.fobj ) this.fobj = wae.create("DATA.File");
		var statstr = this.fobj.readAll("/proc/stat");
		var cpuinfo = statstr.split(/\s+/);
		var totalcpu = 0;
		for( var i = 1; i <= 7 ; i++) {
			var v = parseInt(cpuinfo[i]);
			totalcpu += v;
		}
		var idlecpu = parseInt( cpuinfo[4]);
		if ( isNaN(totalcpu) ) return -1;
		var idlerate = Math.floor((idlecpu-this.idle) * 100 / ( totalcpu - this.total) );
		this.idle = idlecpu;
		this.total = totalcpu;

		return 100 - idlerate;
	}


	this.check1 = function(  ) {
		this.getusage();
		setTimeout( (function() {
			var n = this.getusage();
			this.oncheck1( n );
		}).bind(this), 1000 );
	}

	this.check10 = function() {
		this.usagelist = [];
		if ( !! this.check10_timer )
			clearInterval( this.check10_timer  );

		this.check10_timer = setInterval( (function() {
			this.check1();
		}).bind(this), 1000 * 5 );

		this.oncheck1 = function( n ) {
			// console.log("oncheck1 : " + n + " : " + this.usagelist.length + " : " + JSON.stringify(this.usagelist) );
			this.usagelist.push( n );
			if ( this.usagelist.length < 8 ) 
				return;
			this.usagelist.shift();
			var ulist = this.usagelist;
			this.oncheck10( ulist  );
		}
	}

	this.getavusage = function( ulist ) {
		var nlist = ulist.sort( function(a,b) {return a-b} );
		var sum = 0;
		for(var i=2; i<nlist.length-2; i++ )
			sum += nlist[i];
		return Math.floor( sum/(nlist.length-4) );
	}

	this.onfoundcpulow = function() {
		console.log("found cpu lower!");
		if ( ! this.videoplayerobj ) 
			return;

		this.videoplayerobj.playnext();

	}

	this.start = function( videoplayerobj ) {
		this.videoplayerobj = videoplayerobj;

		this.cpuusage0 = -1;
		this.oncheck10 = function( ulist  ) {
			if ( this.cpuusage0 == -1 ) {
				usage = this.getavusage(ulist);
				this.cpuusage0 = usage;
				console.log("check cpu usage get ussage : "+this.cpuusage0+" : oncheck10: " );
			} else {
				console.log(" check cpu usage , start usage is " + this.cpuusage0 + " : " + JSON.stringify(ulist) );
				for( var i = 0; i<ulist.length; i++ ) {
					if ( ulist[i] > this.cpuusage0 - 20 && ulist[i] > this.cpuusage0/2 ) {
						return;
					}
				}
				console.log(" check cpu usage found all cpu lower");
				this.onfoundcpulow();
			}
		}
		this.check10();
		console.log("start cpu usage check ... " );
	}

	this.cancel_check = function() {
		console.log("cancel cpu usage check");
		this.usagelist = [];
		if ( !! this.check10_timer )
			clearInterval( this.check10_timer  );
		this.check10_timer = null;
		this.cpuusage0 = -1;		
	}
}

// var cpuinfo = new CPUInfo();


function M3u8Checker() {

	this.start = function( url , videoplayerobj ) {
		console.log("start check m3u8 ... ");

		this.videoplayerobj = videoplayerobj;
		this.utime = (new Date()).getTime();
		this.count = 0;
		this.seq = 0;

		if ( !! this.ctimer ) 
			clearInterval( this.ctimer );

		this.murl = url;
		if ( !this.hobj )
			this.hobj = wae.create("Net.HttpClient");
		this.hobj.onComplete = (function( a ) {
			var d = a.arguments[2];
			var p = d.indexOf("EXT-X-MEDIA-SEQUENCE");
			if ( p < 0 ) {
				console.log("invalid data");
				return;
			}
			var s = d.substring( p + 21 );
			var seq = parseInt( s );
			if ( isNaN(seq) ) {
				console.log("invalid seq");
				return;
			}

			var otime = this.utime;
			this.utime = (new Date()).getTime();
			var usec = Math.floor(( this.utime - otime ) / 1000 );
			if ( usec > 20 ) {
				console.log("found broken check m3u8 in "+ usec +"sec, get seq: " + seq );
				this.onm3u8broken();
			}

			if ( ! this.seq ) {
				this.seq = seq;
			} else {
				var seq_inc = seq - this.seq;
				console.log("check m3u8 found seq inc : " + seq_inc + " in " + usec + "sec, seq: " + seq );
				this.seq = seq;
				if (  seq_inc < 0 || seq_inc > 2 ) {
					this.onm3u8broken();
				}
			}
		}).bind(this);

		this.ctimer = setInterval( this.check1.bind(this), 1000 * 10 );
	}

	this.check1 = function() {
		// console.log("check m3u8 ... ");
		this.hobj.getWithAsync2( this.murl ); 
	}

	this.cancel = function() {
		console.log("cancel check m3u8 ... ");
		if ( !! this.ctimer ) 
			clearInterval( this.ctimer );
		this.ctimer = null;
	}

	this.onm3u8broken = function() {
		console.log("found m3u8 broken");

		if ( ! this.videoplayerobj ) 
			return;

		console.log("found m3u8 broken, replay ...");
		this.videoplayerobj.playnext();
	}
}

// var m3u8checker = new M3u8Checker();

function VideoPlayer() {
	this.isPlaying = false;
	this.player = null;
	this.chkTimer = null;
	this.playIdx = -1;
	this.murls = [];
	this.bindEle = null;

	this.init = function(  ) {
		if( this.player != null ) {
			this.oninit();
			return;
		}
		if ( typeof(wae) == "undefined" ) {
			var _this = this;
			setTimeout( function(){ _this.init(); }, 1000 );
			return;
		}
		this.errorcount = 0;
		this.player = wae.create("Media.VideoPlayer");
		this.player.setOnErrorListener();
		this.player.BufferSwitch(2);
		this.fullscreenMode = false;

		var _this = this;
		this.player.onError = function(e) {
			// cpuinfo.cancel_check();
			// m3u8checker.cancel();

			_this.errorcount++;
			console.log( "play error errorcount " + _this.errorcount );
			clearTimeout( _this.chkTimer );
			_this.chkTimer = setTimeout( function() {
					_this.playnext();
				} , 1000 );
			_this.onplayerror();
		}
		this.player.onCompletion = function(e) {
			// cpuinfo.cancel_check();
			// m3u8checker.cancel();

			_this.errorcount = 0;
			clearTimeout( _this.chkTimer );
			_this.chkTimer = setTimeout( function() {
					_this.playnext();
				} , 1000 );
		}
		this.player.onBufferingUpdate = function(e) {
			_this.errorcount = 0;
			// console.log("onBufferingUpdate: "  + JSON.stringify(  e.arguments ) );
			_this.onbuffering( e.arguments[1], e.arguments[2] );
		}
		this.player.onPrepared = function() {
			_this.errorcount = 0;
			if ( _this.fullscreenMode == false && !! _this.bindEle ) {
				var r = _this.getRect();
				if ( r.w <= 0 ) {
					_this.player.stop();
					_this.player.hide();
					_this.isPlaying = false;
					return false;
				}

				// _this.player.setLocation( r.w, r.h , r.x, r.y );
				_this.player.setLocation( r.w+2, r.h+2 , r.x, r.y );
			} else {
				
				// cpuinfo.start( _this );
				// m3u8checker.start( _this.cmurl, _this );

				_this.player.setFullScreen();
				//_this.player.setLocation( 1919, 1279, 0, 0 );				
			}
			_this.player.start();
			// console.log("onPrepared: " )
			_this.onprepared();
		}
		this.oninit();
	}
	this.oninit = function() {}

	this.onplayerror = function() {}

	this.onbuffering = function( rate, status ) {
		console.log("onbuffering " + rate + " : " + status );
	}

	this.onprepared = function() {}

	this.bind = function( ele ) {
		if ( typeof(ele) == "string" )
			this.bindEle = document.getElementById(ele);
		else
			this.bindEle = ele;		
	}

	this.getRect = function() {
		var e = this.bindEle;
		var r = {};
		r.x = 0; r.y = 0; 
		r.w = e.offsetWidth; 
		r.h = e.offsetHeight;
		while( e != null && !!e && e != document.body ) {
			r.x += e.offsetLeft;
			r.y += e.offsetTop;
			e = e.offsetParent;
		}
		return r;
	}

	this.setFullscreen = function( flag ) {
		if ( flag == true ) {
			this.fullscreenMode = true;
			this.player.setFullScreen();

			// cpuinfo.start( this );
			// m3u8checker.start( this.cmurl, this );
		}
		else {
			this.fullscreenMode = false;
			if ( !! this.bindEle ) {
				var r = this.getRect();
				this.player.setLocation( r.w, r.h , r.x, r.y );
			}

			// cpuinfo.cancel_check();
			// m3u8checker.cancel();
		}
	}

	this.playnext = function() {
		if( this.player == null )
			return false;
		if( this.murls.length == 0 )
			return false;
		if( this.fullscreenMode == false )
			this.player.setLocation(2,2,1,1);
		else 
			this.player.setFullScreen();
		//this.player.setFullScreen();
		var murl = this.murls[ (++this.playIdx) % this.murls.length ];
		// console.log("playnext : " + murl + ":" + location.href );
		// console.log("playnext check murl: " + JSON.stringify(this.murls) );
		//this.player.stop();
		this.cmurl = murl;
		this.player.setDataSource( murl );
		//this.player.start();
		this.isPlaying = true;
/*
//		this.startPos = this.player.getCurrentPosition();
		var _this = this;
		setTimeout( function() {
//			var npos = _this.player.getCurrentPosition();
//			if( _this.startPos == npos ) {
//				console.log("playnext : play is not forward : " + _this.startPos + " : " + npos );
				//_this.playnext();
//			}

		}, 1000 * 10 );
*/
		return true;
	}

	this.seturl = function( murl ) {
		// murl = "/mnt/usb_storage/USB_DISK1/udisk0/1.mp4";
		var new_url = getSecUrl(murl );
		console.log("seturl: " + new_url);
		this.murls = [ new_url ];
	}

	this.isVisible = function() {
		if(  ( typeof(this.bindEle) == "undefined" || this.bindEle.offsetWidth <= 0 ) ) {
			return false;
		}
		return true;
	}

	this.checkPlay = function(  ) {
		console.log("checkPlay");
		if(  ( typeof(this.bindEle) == "undefined" || this.bindEle.offsetWidth <= 0 ) ) {
			var _this = this;
			var player = this.player;
			player.onGetStatus = function( a ) {
				var status = a.arguments[0];
//				alert( status );
				if ( status == "Playing" ) {
					_this.player.stop();
					_this.player.hide();
					_this.isPlaying = false;				
				}
			}
			try {
				player.checkStatus();
			}catch(e){
				if( this.isPlaying == true ) {
					_this.player.stop();
					_this.player.hide();
					_this.isPlaying = false;					
				}
			}
		} else if(  typeof(this.bindEle) != "undefined" && this.bindEle.offsetWidth > 0 ) {
			var _this = this;
			var player = this.player;
			player.onGetStatus = function( a ) {
				var status = a.arguments[0];
//				alert( status );
				if ( status != "Playing" ) {
					_this.playnext();
				}
			}
			try {
				player.checkStatus();
			}catch(e){
				if( this.isPlaying == false ) {
					this.playnext();
				}
			}
		}
	}

	this.playTimer = null;
	this.keepPlay = function() {
		clearInterval( this.playTimer );
		var _this = this;
		this.playTimer = setInterval( function(){
			if( _this.murls.length == 0 ) {
				return;
			}
			_this.checkPlay();
		} , 1000 * 10 );
	}

}

